package ua.yandex.bank;

import java.util.concurrent.atomic.AtomicInteger;

public class Account {

    private final int number;
    public final AtomicInteger amountOfMoney;

    Account(int n) {
        number = n;
        amountOfMoney = new AtomicInteger(0);
    }

    public boolean withdraw(int a) {
        while (true) {
            int value = amountOfMoney.get();
            if (a > value) {
                return false;
            }
            int newValue = value - a;
            if (amountOfMoney.compareAndSet(value, newValue)) {
                return true;
            }
        }
    }

    public int number() {
        return this.number;
    }

    public void deposit(int a) {
        if (a < 0) {
            throw new MyException(" Incorrect amount of money ");
        }
        while (true) {
            int value = amountOfMoney.get();
            int newValue = value + a;
            if (amountOfMoney.compareAndSet(value, newValue)) {
                return;
            }
        }
    }

    public int balance() {
        return amountOfMoney.get();
    }
}
